package com.zzy.face.utils.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @Author 朱泽玉
 * @Create 2021/6/26 12:52
 * @Description
 * @Modified By:
 */
//        Claims token = jwt.token(request);
//        token.get("identity"
@Data
@ConfigurationProperties("jwt.config")
public class Jwt {
    // 私钥
    private String key;
    // 失效时间
    private Long ttl;

    public String create(String id, Map<String, Object> map){
        Long now =System.currentTimeMillis();//当前毫秒数
        long exp = now +ttl;
        JwtBuilder builder = Jwts.builder();
        builder.setClaims(map);// 自定义数据
        builder.setId(id) // userId
                .setIssuedAt(new Date())//设置时间
                .signWith(SignatureAlgorithm.HS256,key)//签名私钥
                .setExpiration(new Date(exp));//失效时间
        //创建token
        return builder.compact();
    }

    public Claims parse(String token){
        return Jwts.parser().setSigningKey("zzboy").parseClaimsJws(token).getBody();
    }

    public Claims token(HttpServletRequest request){
        //1、获取token
        String token = request.getHeader("Authorization");
        //2、查看token是否位空
        if (token == null || token.isEmpty()) {
            return null;
        }
        // 3、解析token
        return parse(token);
    }
    public Long getId(HttpServletRequest request) {
        // 1、获取返回的token
        Claims token = this.token(request);
        // 2、判断是否携带token
        if (token == null) {
            return null;
        }
        // 3、获取token中的id值
        return Long.parseLong(token.getId());
    }

//    public boolean checkSign(String token) {
//        try {
//            System.out.println("key:"+key);
//            System.out.println("ttl:"+ttl);
//            Algorithm algorithm  = Algorithm.HMAC256(key);
//            JWTVerifier verifier = JWT.require(algorithm)
//                    //.withClaim("username, username)
//                    .build();
//            verifier.verify(token);
//            return true;
//        }catch (JWTVerificationException e) {
//            throw new RuntimeException("token 无效，请重新获取");
//        }
//    }
}
